//#include <stdio.h>

#include "pc_com.h"
#include <avr/io.h>
#include <avr/interrupt.h>
//#include "avr_compiler.h"
//#include "usart_driver.h"

static FILE mystdout = FDEV_SETUP_STREAM (pc_com_putchar, pc_com_getchar, _FDEV_SETUP_RW);

void pc_com_init()
{
	// TX as output
	PC_PORT.DIRSET = PIN7_bm;
	// RX as input
	PC_PORT.DIRCLR = PIN6_bm;

	PC_USART.CTRLA = (uint8_t) USART_RXCINTLVL_LO_gc;
	PC_USART.CTRLC = (uint8_t) USART_CHSIZE_8BIT_gc | USART_PMODE_DISABLED_gc;
	//PC_USART.BAUDCTRLA = 207;	// Set 9600 Baud
	//PC_USART.BAUDCTRLA = 12;	// Set 9600 Baud (at system clock 2MHz)
	PC_USART.BAUDCTRLA = 0b00010111;
	PC_USART.BAUDCTRLB = 0b10100100;
	

	PC_USART.CTRLB |= USART_RXEN_bm;
	PC_USART.CTRLB |= USART_TXEN_bm;

	stdout = &mystdout;
	stdin = &mystdout;
}

int pc_com_putchar(char c, FILE *stream)
{
	while( (PC_USART.STATUS & USART_DREIF_bm) == 0 ) {}
	PC_USART.DATA = c;
	return 1;
}
 
int pc_com_getchar(FILE *stream)
{
	while( (PC_USART.STATUS & USART_RXCIF_bm) == 0 ) {}
	return PC_USART.DATA;
}

char get_char_nonblocking()
{
		if (PC_USART.STATUS & USART_RXCIF_bm)
			return PC_USART.DATA;
		else
			return 0;
}


ISR(USARTE0_RXC_vect)
{

//	PORTD.OUTTGL |= PIN1_bm;
	PC_USART.DATA = PC_USART.DATA;
}


ISR(USARTE0_DRE_vect)
{
//	PORTC.OUT |= PIN5_bm;
}

